//
//  SLWebViewController.m
//  SulitLoan
//
//  Created by 虞嘉伟 on 2025/2/23.
//

#import "SLWebViewController.h"
#import <WebKit/WebKit.h>
#import <YYKit.h>
#import <Masonry.h>

#import "AppGradeMessage.h"
#import "CloseH5Message.h"
#import "JumpToHomeMessage.h"
#import "OpenMailMessage.h"
#import "OpenURLMessage.h"
#import "UploadRiskMessage.h"

@interface SLWebViewController ()<WKNavigationDelegate, WKUIDelegate, WKScriptMessageHandler>
@property (nonatomic, strong) WKWebView *webView;

@property (nonatomic, strong) UIProgressView *progressView;

@property (nonatomic, strong) NSMutableArray<id<JSMessageProtocol>> *messageHandlers;
@end

@implementation SLWebViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    @weakify(self);
    [self showNavBar:@"" backBlock:^{
        @strongify(self);
        if (self.webView.canGoBack) {
            [self.webView goBack];
        } else {
            [self.navigationController popToRootViewControllerAnimated:YES];
        }
    }];
    [self.view addSubview:self.webView];
    [self.webView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(self.view);
        make.top.equalTo(self.navBar.mas_bottom);
    }];
    
    [self.navBar addSubview:self.progressView];
    [self.progressView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(self.navBar);
        make.height.mas_equalTo(2);
    }];
    
    // 添加 JS 消息处理
    AppGradeMessage *app = [[AppGradeMessage alloc] initWithController:self];
    CloseH5Message *close = [[CloseH5Message alloc] initWithController:self];
    JumpToHomeMessage *jump = [[JumpToHomeMessage alloc] initWithController:self];
    OpenMailMessage *mail = [[OpenMailMessage alloc] initWithController:self];
    OpenURLMessage *url = [[OpenURLMessage alloc] initWithController:self];
    UploadRiskMessage *risk = [[UploadRiskMessage alloc] initWithController:self];
    [self registerMessageHandler:app];
    [self registerMessageHandler:close];
    [self registerMessageHandler:jump];
    [self registerMessageHandler:mail];
    [self registerMessageHandler:url];
    [self registerMessageHandler:risk];
}
- (WKWebView *)webView {
    if (!_webView) {
        
        // 创建 WKWebView 配置
        WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
        
        // 创建 WKUserContentController 对象
        WKUserContentController *userContentController = [[WKUserContentController alloc] init];
        
        // 添加 JS 消息处理
        
        // 将 WKUserContentController 对象设置到配置对象中
        config.userContentController = userContentController;
        
        // 创建 WKWebView
        _webView = [[WKWebView alloc] initWithFrame:CGRectZero configuration:config];
        _webView.navigationDelegate = self; // 设置导航代理
        _webView.UIDelegate = self;
        // 监听 estimatedProgress
        [_webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
    }
    return _webView;
}
- (UIProgressView *)progressView {
    if (!_progressView) {
        _progressView = [[UIProgressView alloc] initWithProgressViewStyle:UIProgressViewStyleBar];
        _progressView.tintColor = [UIColor blueColor]; // 进度条颜色
        _progressView.trackTintColor = [UIColor clearColor]; // 背景色
    }
    return _progressView;
}
- (NSMutableArray *)messageHandlers {
    if (!_messageHandlers) {
        _messageHandlers = [NSMutableArray array];
    }
    return _messageHandlers;
}
- (void)loadURL:(NSString *)url {
    if (url.length == 0) {
        return;
    }
    // 加载网页
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
    [self.webView loadRequest:request];
}

- (void)registerMessageHandler:(id<JSMessageProtocol>)handler {
    [self.messageHandlers addObject:handler];
    
    WKUserContentController *userContentController = _webView.configuration.userContentController;
    [userContentController addScriptMessageHandler:self name:handler.name];
}

// 添加 WKScriptMessageHandler 代理方法
#pragma mark - WKScriptMessageHandler
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
    // 处理来自 JS 的消息
    for (id<JSMessageProtocol>handler in self.messageHandlers) {
        if ([message.name isEqualToString:handler.name]) {
            [handler handleMessage:message];
        }
    }
}

#pragma mark - WKNavigationDelegate
// 页面开始加载时调用
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation {
    NSLog(@"页面开始加载");
}
// 页面加载完成时调用
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    NSLog(@"页面加载完成");
    self.navBar.titleLabel.text = webView.title;
}

// 页面加载失败时调用
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error {
    NSLog(@"页面加载失败: %@", error.localizedDescription);
}

// 在收到响应后决定是否跳转
- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler {
    // 允许跳转
    decisionHandler(WKNavigationResponsePolicyAllow);
}

// 在发送请求之前决定是否跳转
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
    // 允许跳转
    decisionHandler(WKNavigationActionPolicyAllow);
}

// 监听 estimatedProgress 并更新进度条
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
    if ([keyPath isEqualToString:@"estimatedProgress"]) {
        // 更新进度条
        self.progressView.progress = self.webView.estimatedProgress;
        
        // 加载完成后隐藏进度条
        if (self.webView.estimatedProgress >= 1.0) {
            [UIView animateWithDuration:0.3 delay:0.3 options:UIViewAnimationOptionCurveEaseOut animations:^{
                self.progressView.alpha = 0;
            } completion:^(BOOL finished) {
                self.progressView.progress = 0;
                self.progressView.alpha = 1;
            }];
        }
    }
}

- (void)dealloc {
    // 移除 KVO 监听
    [self.webView removeObserver:self forKeyPath:@"estimatedProgress"];
    
    // 移除 JS 消息处理
    for (id<JSMessageProtocol>handler in self.messageHandlers) {
        [self.webView.configuration.userContentController removeScriptMessageHandlerForName:handler.name];
    }
}
@end
